<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Galleries extends Users_Controller {
	
	function __construct()
	{
		parent::__construct();
	}

	function index()
	{
		$g = new Gallery();
		$g->where_related_user('id', $this->tank_auth->get_user_id())->get();
				
		$this->imageene->user('galleries/list', array('galleries' => $g));
	}
	
	function show($id = NULL)
	{
		$g = $this->_is_user_gallery($id, $this->tank_auth->get_user_id());
		$this->imageene->user('galleries/detail', array('g'=>$g));
	}
	
	function create()
	{
		$data['name'] = $this->input->post('name');
		$data['description'] = $this->input->post('description');
		$data['published'] = $this->input->post('published');
		
		if($this->input->post('submit')) {
			$u = new User();
			$u->where('id', $this->tank_auth->get_user_id())->get();
			
			$g = new Gallery();
			$g->uid = (int)$u->id;
			$g->name = $data['name'];
			$g->description = $data['description'];
			$g->published = $data['published'];
			$g->date_published = ($g->published) ? date("Y-m-d H:i:s") : date('0000-00-00 00:00:00');
			
			$data["g"] = $g;
			
			if($g->save())
			{
				if($u->save($g)) {
					redirect('/user/galleries');
				}
			}
		}
		
		$this->imageene->user('galleries/create', $data);
	}
	
	function edit($id=NULL)
	{
		$g = $this->_is_user_gallery($id, $this->tank_auth->get_user_id());
		
		if($this->input->post('submit')) {
			$g->name		= $this->input->post('name');
			$g->description	= $this->input->post('description');
			$g->published	= $this->input->post('published');
			$g->date_published = ($g->published) ? date("Y-m-d H:i:s") : date('0000-00-00 00:00:00');
			
			if($g->save())
			{
				redirect("/user/galleries/show/{$g->id}");
			}
		}
		
		$this->imageene->user('galleries/edit', array('g'=>$g));
	}
	
	function delete($id=NULL)
	{
		$g = $this->_is_user_gallery($id, $this->tank_auth->get_user_id());
		
		$this->imageene->user('galleries/delete', array('g'=>$g));
	}
	
	function confirm_delete($id=NULL)
	{
		$g = $this->_is_user_gallery($id, $this->tank_auth->get_user_id());
	
		$g->delete();
		
		redirect("/user/galleries/");
	}
	
	private function _is_user_gallery($id = NULL, $user_id=NULL) {
	
		$g = new Gallery();
		$g->where('uid', $user_id);
		$g->where('id', $id)->limit(1)->get();
	
		if(is_null($id) || $g->result_count() == 0)
		{
			redirect('/user/galleries');
		}
	
		return $g;
	}
}
	
/* End of file galleries.php */
/* Location: ./application/controllers/user/galleries.php */